package com.zygh.lz.stapprove;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;

/**
 * 省厅出参解析
 */
public class OutBeanUtil {

    public static <T> OutBean resSuc(T data, InBean inBean) {
        return res(data, inBean, true, null);
    }

    public static <T> OutBean resSucCode(T data, InBean inBean, Integer code) {
        // 构建返回数据对象
        OutBean.OutBeanData.FiledVal.Val val = new OutBean.OutBeanData.FiledVal.Val();
        val.setValue(data != null ? JSON.toJSONString(data) : null);

        // 构建返回数据列表
        List<OutBean.OutBeanData.FiledVal.Val> vals = new ArrayList<>();
        vals.add(val);

        // 构建返回字段列表对象
        OutBean.OutBeanData.FiledVal filedVal = new OutBean.OutBeanData.FiledVal();
        filedVal.setFieldValues(vals);

        // 构建返回字段列表
        List<OutBean.OutBeanData.FiledVal> filedValList = new ArrayList<>();
        filedValList.add(filedVal);

        OutBean.OutBeanData outBeanData = new OutBean.OutBeanData();
        outBeanData.setDataList(filedValList);

        OutBean outBean = new OutBean();
        outBean.setCode(code)
                .setMessage("操作成功")
                .setMessageId(inBean.getMessageId())
                .setVersion(inBean.getVersion())
                .setData(outBeanData);

        return outBean;
    }

    public static <T> OutBean resErr(String msg, InBean inBean) {
        return res(null, inBean, false, msg);
    }


    private static <T> OutBean res(T data, InBean inBean, boolean isSuc, String msg) {
        // 构建返回数据对象
        OutBean.OutBeanData.FiledVal.Val val = new OutBean.OutBeanData.FiledVal.Val();
        val.setValue(data != null ? JSON.toJSONString(data) : null);

        // 构建返回数据列表
        List<OutBean.OutBeanData.FiledVal.Val> vals = new ArrayList<>();
        vals.add(val);

        // 构建返回字段列表对象
        OutBean.OutBeanData.FiledVal filedVal = new OutBean.OutBeanData.FiledVal();
        filedVal.setFieldValues(vals);

        // 构建返回字段列表
        List<OutBean.OutBeanData.FiledVal> filedValList = new ArrayList<>();
        filedValList.add(filedVal);

        OutBean.OutBeanData outBeanData = new OutBean.OutBeanData();
        outBeanData.setDataList(filedValList);

        OutBean outBean = new OutBean();
        outBean.setCode(isSuc ? 200 : 500)
                .setMessage(isSuc ? "操作成功" : StrUtil.isNotBlank(msg) ? msg : "操作失败")
                .setMessageId(inBean.getMessageId())
                .setVersion(inBean.getVersion())
                .setData(outBeanData);

        return outBean;
    }

}
